# -*- coding: UTF-8 -*-

# @Time : 2020/8/26 11:14 

# @Author : litao

# @File : index.py 
import tornado.escape
import tornado.web
from models import User
from handlers.base import BaseHandler

class IndexHandler(BaseHandler):
    def get(self):
        # self.write("hello world")
        self.render('index.html')

    def post(self):
        username = self.get_argument("username")
        password = self.get_argument("password")
        user = User.objects.filter(username=username)
        if user:

            if user[0].password == password:
                self.set_current_user(username)  # 将当前用户名写入 cookie，方法见下面

                #self.set_secure_cookie(username, password, httponly=True, secure=True) #self.get_secure_cookie(username) utf8
                self.write(username)
            else:
                self.write("-1")
        else:
            self.write("-1")

    def set_current_user(self, user):
        if user:
            self.set_secure_cookie("user", tornado.escape.json_encode(user))  # 注意这里使用了 tornado.escape.json_encode() 方法
        else:
            self.clear_cookie("user")


class ErrorHandler(BaseHandler):  # 增加了一个专门用来显示错误的页面
    def get(self):  # 但是后面不单独讲述，读者可以从源码中理解
        self.render("error.html")